package com.msf.tutorial.java8.chapter1;

import com.msf.tutorial.java8.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 第四种状态：使用匿名类，简化代码
 *
 * 优点：
 * 比起第三种状态，代码实现简化
 *
 * 缺点：
 * 不易理解
 */
public class Step4 {

    interface AppleFilter {
        boolean test(Apple apple);
    }

    /**
     * 把颜色作为参数
     */
    public static List<Apple> filterApples(List<Apple> inventory, AppleFilter filter) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory) {
            if ( filter.test(apple) ) {
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {

        List<Apple> list = Arrays.asList(
            new Apple(1L, "red", 1D),
            new Apple(2L, "red", 2D),
            new Apple(3L, "green", null),
            new Apple(1L, "green", 3D)
        );

        List<Apple> greenApples = filterApples(list, new AppleFilter() {
            @Override
            public boolean test(Apple apple) {
                return "green".equals(apple);
            }
        });
        List<Apple> redApples = filterApples(list, new AppleFilter() {
            @Override
            public boolean test(Apple apple) {
                return "red".equals(apple);
            }
        });

        System.out.println(greenApples);
        System.out.println(redApples);
    }

}
